package com.auto.survey.activity.monitoring.ctrlmeasure

import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.auto.survey.R
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.ClosedLoopObservation
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CtrlTaskAddActivity : BaseActivity() {
    private var projectId:Int = -1
    private var objectId:Int = -1
    private var stationId:Int = -1

    private val database = MonitoringRepository()

    override fun initView() {
        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("新建任务")

        val edit = findViewById<EditText>(R.id.edit_ctrl_addtask)
        edit.setText(Helper.formatTimestamp(System.currentTimeMillis(), "yyyyMMddHHmmss"))

        findViewById<TextView>(R.id.tv_ctrl_addtask).setOnClickListener {
            if (TextUtils.isEmpty(edit.text.toString())) {
                CentreToast.instance.show("名称不可为空",false)
                return@setOnClickListener
            }
            val taskbean = ClosedLoopObservation(monitoringObjectId=objectId, stationId=stationId, loopName=edit.text.toString(), startPointId=null, endPointId=null)
            lifecycleScope.launch {
                withContext(Dispatchers.Main) {
                    val taskid = database.addCtrlTask(taskbean)
                    if (taskid.toInt() != -1) {
                        CentreToast.instance.show("添加任务成功", true)
                    } else {
                        CentreToast.instance.show("添加任务失败", true)
                    }

                    finish()
                }
            }


        }

    }

    override fun getLayoutId(): Int {

        return R.layout.activity_ctrl_addtask
    }
}